﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using FrameWorkSystem.BusinessLayer;
namespace FrameWorkSystem.PhanQuyen
{
    public enum TypeOfFunc
    {
        Menu,
        Tree
    }
    public partial class frmSetPemission : BaseForm //DevComponents.DotNetBar.Office2007Form
    {
        TypeOfFunc _typeFunc = TypeOfFunc.Tree;

        public string TypeFunc
        {
            get
            {
                if (_typeFunc == TypeOfFunc.Tree)
                    return "TV";
                return "MN"; 
            }            
        }
        SortedList<string, TreeNode> lstFuc;

        #region Contructors
        public frmSetPemission()
        {
            InitializeComponent();
        }
        public frmSetPemission(TreeView twappFunc)
        {
            InitializeComponent();
            foreach (TreeNode node in twappFunc.Nodes)
            {
                TreeNode _funNode = node.Clone() as TreeNode;
                this.twFunction.Nodes.Add(_funNode);
            }

            _typeFunc = TypeOfFunc.Tree;
        }
        public frmSetPemission(MenuStrip mnuFuction)
        {
            InitializeComponent();
            //
            Queue<ToolStripMenuItem> _QMnuItem = new Queue<ToolStripMenuItem>(mnuFuction.Items.Count);

            lstFuc = new SortedList<string, TreeNode>();
            //
            TreeNode _newnode, parent_node;
            // Lấy các menu mức 1 để add vào root
            foreach (ToolStripMenuItem mnu in mnuFuction.Items)
            {                
                _newnode = new TreeNode(mnu.Text);
                _newnode.Name = mnu.Name;

                lstFuc.Add(_newnode.Name,_newnode);
                _QMnuItem.Enqueue(mnu);
                twFunction.Nodes.Add(_newnode);
                
            } 
            // 
            ToolStripMenuItem mnuParent, mnuChild;
            while (_QMnuItem.Count > 0)
            {
                mnuParent = _QMnuItem.Dequeue();
                // Tìm node cha
                lstFuc.TryGetValue(mnuParent.Name, out parent_node);
                foreach (ToolStripItem item in mnuParent.DropDownItems)
                {
                    _newnode = new TreeNode(item.Text);
                    _newnode.Name = item.Name;
                    // add vào node cha                    
                    parent_node.Nodes.Add(_newnode);
                    //
                    lstFuc.Add(_newnode.Name, _newnode);

                    mnuChild = item as ToolStripMenuItem;
                    if (mnuChild != null)
                        _QMnuItem.Enqueue(mnuChild);
                }
            }
            //
            _typeFunc = TypeOfFunc.Menu;
        }  
        #endregion
        
        private void frmSetPemission_Load(object sender, EventArgs e)
        {
            mnuGroup_User.Opened+=new EventHandler(mnuGroup_User_Opened);
            LoadUsers();
            // Đưa các node tree các chức năng vào danh sách sắp xếp
            ListFunction();
        }
        private void ListFunction()
        {
            lstFuc = new SortedList<string, TreeNode>();
            Queue<TreeNode> _QNode = new Queue<TreeNode>(100);
           
            foreach(TreeNode node in twFunction.Nodes)
            {
                _QNode.Enqueue(node);                
            }
            while (_QNode.Count != 0)
            {
                TreeNode dx = _QNode.Dequeue();
                lstFuc.Add(dx.Name, dx);
                foreach (TreeNode item in dx.Nodes)
                    _QNode.Enqueue(item);
            }
        }
        private void LoadUsers()        
        {
            try
            {
                // Load group
                Sys_UserGroupsFactory objUGDao = new Sys_UserGroupsFactory();
                List<Sys_UserGroups> lstGroup = objUGDao.GetAll();
                int i;
                TreeNode root;
                for (i = 0; i < lstGroup.Count; i++)
                {
                    root = new TreeNode(lstGroup[i].Name);
                    root.Name = lstGroup[i].ID_Group;
                    twUsers.Nodes.Add(root);
                }
                // Load toan bo cac user
                Sys_UsersFactory objUserDao = new Sys_UsersFactory();
                List<Sys_Users> lstUsers = objUserDao.GetAll();
                TreeNode child;
                for (i = 0; i < lstUsers.Count; i++)
                {
                    child = new TreeNode(lstUsers[i].User_Name+ " - " + lstUsers[i].Full_Name);
                    child.Name = lstUsers[i].User_Name;
                    child.Tag = lstUsers[i].Full_Name;
                    twUsers.Nodes[lstUsers[i].Group_ID].Nodes.Add(child);
                }
            }
            catch { MessageBox.Show("Lỗi lấy dữ liệu người dùng - nhóm người dùng"); }            
        }
        private void mnuGroup_User_Opened(object sender, EventArgs e)
        {
            TreeNode _node = twUsers.SelectedNode;
            if (_node == null)
                return;
            else
            {
                mnuGroup_User.Visible = true;
                bool isParent = _node.Parent == null;

                mnuAddGroup.Visible = isParent;
                mnuEditGroup.Visible = isParent;
                mnuDeleteGroup.Visible = isParent;

                mnuSpace1.Visible = isParent;
                //mnuAddUser.Visible = !isParent;
                mnuEditUser.Visible = !isParent;
                mnuDeleteUser.Visible = !isParent;
            }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
                this.Close();
            base.OnKeyDown(e);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            TreeNode nodeSelected = twUsers.SelectedNode;
            if (nodeSelected.Parent == null)
            {
                MessageBox.Show("Bạn chưa chọn user để phân quyền");
                return; //Là node nhóm người dùng
            }

            Sys_UserPermissionFactory objDao = new Sys_UserPermissionFactory();
            Sys_UserPermission objEntity = new Sys_UserPermission();
            objDao.Delete(Sys_UserPermission.Sys_UserPermissionFields.UserName, nodeSelected.Name);
            
            objEntity.UserName = nodeSelected.Name;
            objEntity.TypeOfFunc = TypeFunc;
            objEntity.IsEnable = false;
            objEntity.IsVisible = false;

            for (int i=0; i<lstFuc.Values.Count; i++)
                if (!lstFuc.Values[i].Checked)
                {
                    objEntity.FuncName = lstFuc.Values[i].Name;
                    objDao.Insert(objEntity);
                }
            MessageBox.Show("Đã lưu phân quyền của user:'" + txt_Uname.Text+"' xong");
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void twFunction_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Checked)
                if (e.Node.Parent != null)
                    e.Node.Parent.Checked = true;
        }

        private void twUsers_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Parent == null) return; // Node nhóm người dùng
            // Tên người dùng
            string uName = e.Node.Name;            
            Sys_UserPermissionFactory objUPermisDao = new Sys_UserPermissionFactory();
            List<Sys_UserPermission> lstPermis = objUPermisDao.GetNoPermission(uName, _typeFunc);

            TreeNode node;
            // Thiết lập tất cả các node về true (được quyền)
            foreach (TreeNode item in lstFuc.Values)
                item.Checked = true;
            int i;
            // Vô hiệu hóa các chức năng không được quyền
            for (i = 0; i < lstPermis.Count; i++)
            {
                if (lstFuc.TryGetValue(lstPermis[i].FuncName, out node))
                    node.Checked = false;
            }
            txt_Uname.Text = uName;
            txt_Hoten.Text = e.Node.Tag.ToString();
        }
        #region Thêm sửa thông tin người dùng
        private void mnuAddGroup_Click(object sender, EventArgs e)
        {
            frmU_GroupNewEdit NE_Form = new frmU_GroupNewEdit();
            NE_Form.OnAddNewEntity = new EventHandler(OnAddNewGroup);
            NE_Form.ShowDialog();
        }
        private void OnAddNewGroup(object objGroup, EventArgs e)
        {
            Sys_UserGroups objEntity = objGroup as Sys_UserGroups;
            if (objEntity != null)
            {
                TreeNode newnode = new TreeNode(objEntity.Name);
                newnode.Name = objEntity.ID_Group;
                twUsers.Nodes.Add(newnode);
            }
        }
        private void mnuEditGroup_Click(object sender, EventArgs e)
        {
            TreeNode root = twUsers.SelectedNode;
            frmU_GroupNewEdit edit_Form = new frmU_GroupNewEdit(new Sys_UserGroups(root.Name,root.Text));
            edit_Form.OnEditEntity += new EventHandler(OnUpdateUserGroup);
            edit_Form.ShowDialog();
        }
        private void OnUpdateUserGroup(object objGroup, EventArgs e)
        {
            Sys_UserGroups objEntity = objGroup as Sys_UserGroups;
            if (objEntity != null)
                twUsers.SelectedNode.Text = objEntity.Name;
        }
        private void mnuDeleteGroup_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn chắc chắn xóa nhóm này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {
                Sys_UserGroupsFactory objDao = new Sys_UserGroupsFactory();
                if (objDao.Delete(new Sys_UserGroupsKeys(twUsers.SelectedNode.Name)))
                {
                    twUsers.SelectedNode.Remove();
                    MessageBox.Show("Đã xóa thành công");
                }
            }
        }

        private void mnuAddUser_Click(object sender, EventArgs e)
        {
            frmUserNewEdit frmNewEdit = new frmUserNewEdit();
            frmNewEdit.OnAddNewEntity += new EventHandler(OnAddNewUser);
            frmNewEdit.UserGroupID = CurrentGroupID();
            frmNewEdit.ShowDialog();
        }
        private void OnAddNewUser(object objUser, EventArgs e)
        {
            Sys_Users objEntity = objUser as Sys_Users;
            if (objEntity == null) return;
            TreeNode root = twUsers.Nodes[objEntity.Group_ID];            
            TreeNode newnode = new TreeNode(objEntity.User_Name+ " - " + objEntity.Full_Name);
            newnode.Name = objEntity.User_Name;
            newnode.Tag = objEntity.Full_Name;
            //
            root.Nodes.Add(newnode);
        }
        private void mnuEditUser_Click(object sender, EventArgs e)
        {
            Sys_UsersFactory objDao = new Sys_UsersFactory();
            Sys_Users objEntity = objDao.GetByPrimaryKey(new Sys_UsersKeys(twUsers.SelectedNode.Name));

            frmUserNewEdit frmNewEdit = new frmUserNewEdit(objEntity);
                frmNewEdit.OnUpdateEntity += new EventHandler(OnEditUser);
            frmNewEdit.ShowDialog();
        }
        private void OnEditUser(object objUser, EventArgs e)
        {
            Sys_Users objEntity = objUser as Sys_Users;
            if (objEntity == null) return;
            TreeNode editnode = twUsers.SelectedNode;
            editnode.Text = objEntity.User_Name+ " - " + objEntity.Full_Name;
            editnode.Name = objEntity.User_Name;
            editnode.Tag = objEntity.Full_Name;            
        }
        private void mnuDeleteUser_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn chắc chắn xóa User đã chọn", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.No) return;
            Sys_UsersFactory objDao = new Sys_UsersFactory();
            if (objDao.Delete(new Sys_UsersKeys(twUsers.SelectedNode.Name)))
                twUsers.SelectedNode.Remove();
        }
        private string CurrentGroupID()
        {
            string gr_ID = twUsers.SelectedNode.Name;
            if (twUsers.SelectedNode.Parent != null)
                gr_ID = twUsers.SelectedNode.Parent.Name;
            return gr_ID;
        }
        #endregion
    }
}
